package com.qf.pck.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.pck.entity.Package;
import com.qf.pck.entity.PackageOrder;
import com.qf.pck.entity.PackageTenantPerms;
import com.qf.pck.mapper.PackageMapper;
import com.qf.pck.mapper.PackageOrderMapper;
import com.qf.pck.mapper.PackageTenantPermsMapper;
import com.qf.pck.service.PackageService;
import com.qf.tenant.entity.Tenant;
import com.qf.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 租户套餐表 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2023-10-27
 */
@Service
public class PackageServiceImpl extends ServiceImpl<PackageMapper, Package> implements PackageService {


    @Autowired
    private PackageTenantPermsMapper packageTenantPermsMapper;

    @Autowired
    private PackageOrderMapper packageOrderMapper;

    @Override
    public R<List<Package>> listPck() {

        //获取所有的套餐
        QueryWrapper<Package> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Package::getStatus, 0);
        List<Package> packages = this.baseMapper.selectList(queryWrapper);

        Tenant tenant = (Tenant) SecurityContextHolder.getContext().getAuthentication().getPrincipal();


        for (Package pck : packages) {
            List<PackageOrder> packageOrders = packageOrderMapper.selectOrder(tenant.getId(), pck.getId());
            if (packageOrders.size() != 0 && packageOrders != null) {
                for (PackageOrder packageOrder : packageOrders) {
                    if (packageOrder.getEndTime().compareTo(new Date()) > 0) {
                        pck.setState(1);
                    }else {
                        pck.setState(0);
                    }
                }
            }
            String permIds = pck.getPermIds();

            List<String> permIdsList = JSONUtil.toList(permIds, String.class);


            List<PackageTenantPerms> collect = permIdsList.stream().map(id -> {
                return packageTenantPermsMapper.selectById(id);
            }).collect(Collectors.toList());

            pck.setPerms(collect);

        }


        return R.ok(packages);
    }


}
